/*
 * @(#)RuntimeUtil.java	1.0 Mar 7, 2008
 *
 *	The MIT License
 *
 *	Copyright (c) 2008 Malachi de AElfweald <malachid@gmail.com>
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
package org.eoti.util;

import java.util.concurrent.*;

public class RuntimeUtil
{
	public static StackTraceElement whoAmI()
	{
		// [0] = getStackTrace()
		// [1] = whoAmI()
		// [2] = who called whoAmI()
		return (getStackTrace())[2];
	}

	public static StackTraceElement whoCalledMe()
	{
		// [0] = getStackTrace()
		// [1] = whoAmI()
		// [2] = who called whoAmI()
		// [3] = the one who called the one who called whoAmI()
		return (getStackTrace())[3];
	}

	public static StackTraceElement whoCalledMe(int depthAboveMe)
	{
		// [0] = getStackTrace()
		// [1] = whoAmI()
		// [2] = who called whoAmI()
		// [3] = the one who called the one who called whoAmI()
		return (getStackTrace())[3 + depthAboveMe];
	}

	protected static StackTraceElement[] getStackTrace()
	{
		try{
			throw new Exception("getStackTrace()");
	    }catch (Exception e) {
	    	return e.getStackTrace();
	    }
	}

	protected static ConcurrentHashMap<ShutdownHookListener,ExitShutdownHook> shutdownHooks;

	public static void addShutdownHook(ShutdownHookListener listener)
	{
		if(listener == null)
			return;

		if(shutdownHooks == null)
			shutdownHooks = new ConcurrentHashMap<ShutdownHookListener,ExitShutdownHook>();

		ExitShutdownHook hook = new ExitShutdownHook(listener);
		shutdownHooks.put(listener, hook);
		Runtime.getRuntime().addShutdownHook( hook );
	}

	public static void removeShutdownHook(ShutdownHookListener listener)
	{
		if(shutdownHooks == null)
			return;

		if(listener == null)
			return;

		ExitShutdownHook hook = shutdownHooks.get(listener);
		shutdownHooks.remove(listener);
		Runtime.getRuntime().removeShutdownHook(hook);
	}
}
